package lib

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
)

const (
	LoginUrl string = "http://www.ymiot.net/Login/WMLogin" //登录系统
)

//WMLogin 登录系统
func WMLogin(userName, password string) (*LoginResponse, error) {
	r, err := http.Post(LoginUrl, "application/x-www-form-urlencoded",
		bytes.NewReader([]byte(fmt.Sprintf("Account=%s&Pwd=%s&channel=false", userName, NewPwd(password)))))
	if err != nil {
		return nil, err
	}

	defer func() {
		_ = r.Body.Close()
	}()
	cookies := r.Cookies()
	lr := LoginResponse{}

	for _, r := range cookies {
		if r.Name == "acw_tc" {
			lr.AcwTc = r.Value
		}

		if r.Name == "AdminSession" {
			lr.AdminSession = r.Value
		}
	}

	responseData, err := ioutil.ReadAll(r.Body)
	if err != nil {
		return nil, err
	}

	resp := struct {
		Success bool   `json:"Success"`
		Message string `json:"Message"`
		Code    string `json:"Code"`
		//Data    struct {
		//	AdminName      string `json:"Admin_Name"`
		//	PowerGroupName string `json:"PowerGroup_Name"`
		//} `json:"Data"`
	}{}

	err = json.Unmarshal(responseData, &resp)
	if err != nil {
		return nil, err
	}

	lr.Message = resp.Message
	lr.Success = resp.Success
	return &lr, nil
}
